/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConfigurarCampeonato.java
 *
 * Created on 24/06/2011, 18:32:06
 */
package GUI.campeonato;

import GUI.escola.SelecionaEscola;
import bd.MySql;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import util.Datas;

/**
 *
 * @author Gabriel
 */
public class ConfigurarCampeonato extends javax.swing.JFrame {

    private ArrayList<Integer> idNovos;
    private ArrayList<Integer> idAntigos;

    /** Creates new form ConfigurarCampeonato */
    public ConfigurarCampeonato() {
        initComponents();
        this.setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Configurar Campeonato");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Campeonato"));

        jLabel1.setText("ID:");

        jTextField1.setColumns(5);

        jButton1.setText("...");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Estado:");

        jLabel3.setText("XX");

        jLabel4.setText("Ano:");

        jLabel5.setText("XXXX");

        jLabel6.setText("Data Início:");

        jLabel7.setText("XX/XX/XXXX");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel2)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jButton1)
                    .addComponent(jLabel5)
                    .addComponent(jLabel7))
                .addContainerGap(306, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Escolas Participantes"));

        tableModel = new TableModelEscolas();
        jTable1.setModel(tableModel);
        jScrollPane1.setViewportView(jTable1);

        jButton2.setText("Adicionar Escola...");
        jButton2.setEnabled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 447, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton2))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton3.setText("Cancelar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Ok");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton4))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // exibe uma caixa de diálogo para seleção da escola participante
        SelecionaEscola s = new SelecionaEscola(this, true);
        int id = s.showDialog();

        if (id != -1) { // se o usuário não selecionou nenhuma escola, exibe mensagem de erro
            if(idAntigos.contains(new Integer(id))) {
                JOptionPane.showMessageDialog(this, "Escola já participa do campeonato", "Erro", JOptionPane.ERROR_MESSAGE);
            } else { // senão, insere a escola participante no campeonato
                MySql conn = new MySql(GUI.Main.config);

                idNovos.add(id);

                String nomeEscola = conn.getTable("SELECT nomeCompleto FROM escola WHERE idEscola=" + id).get(0).get(0);

                String data[] = new String[2];

                data[0] = String.valueOf(id);
                data[1] = nomeEscola;

                tableModel.addData(data);
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    // permite selecionar o campeonato e exibe seus dados
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        SelecionarCampeonato s = new SelecionarCampeonato(this, true);

        int id = s.showDialog();

        if (id != -1) { // se um campeonato foi escolhido, exibe os dados
            MySql conn = new MySql(GUI.Main.config);
            jTextField1.setText(String.valueOf(id));
            ArrayList<ArrayList<String>> resultado = conn.getTable("SELECT estado,anoRealizacao,dataInicio FROM campeonato_estadual WHERE idCampeonato=" + id);

            jLabel3.setText(resultado.get(0).get(0));
            jLabel5.setText(Datas.MySQLDateToJavaDate(resultado.get(0).get(1)).getYear() + "");
            jLabel7.setText(Datas.MySQLDateToJavaDate(resultado.get(0).get(2)).toString());

            resultado = conn.getTable("SELECT escola.idEscola,escola.nomeCompleto,EscolaPart.grupo FROM escola JOIN (SELECT idEscola,grupo FROM escola_participante WHERE idCampeonato=" + id + ") as EscolaPart ON EscolaPart.idEscola=escola.idEscola");

            System.out.println(resultado.size());

            idAntigos = new ArrayList<Integer>();
            idNovos = new ArrayList<Integer>();

            for (int i = 0; i < resultado.size(); i++) {
                String data[] = new String[3];
                for (int j = 0; j < resultado.get(i).size(); j++) {
                    if (j == 0) {
                        idAntigos.add(Integer.valueOf(resultado.get(i).get(j)));
                    }
                    data[j] = resultado.get(i).get(j);
                }
                tableModel.addData(data);
            }
            jButton2.setEnabled(true);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    // quando o usuário clica em OK, as alterações feitas são passadas ao banco de dados
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        if(jButton2.isEnabled()) {
            int linhas = jTable1.getRowCount();

            for(int i=0;i<linhas;i++) {
                int id = Integer.valueOf(jTable1.getValueAt(i, 0).toString());

                if(!idAntigos.contains(new Integer(id))) {
                    Object grupo = jTable1.getValueAt(i, 2);
                    Object dataInicio = jTable1.getValueAt(i, 3);
                    Object horaDesfile = jTable1.getValueAt(i, 4);

                    if(dataInicio != null && horaDesfile != null) {
                        MySql conn = new MySql(GUI.Main.config);

                        String stringGrupo;

                        if(grupo == null) {
                            stringGrupo = "";
                        } else {
                            stringGrupo = grupo.toString();
                        }

                        String stringDataInicio = Datas.JavaDateToMySQLDate(dataInicio.toString());
                        String stringDataInicioHoraInicio = stringDataInicio + " " + horaDesfile.toString();

                        String query = "INSERT INTO escola_participante(idEscola,idCampeonato,grupo,inicioDesfile,dataDesfile) VALUES (" + id + "," + jTextField1.getText() + ",\"" +  stringGrupo + "\",\"" + stringDataInicioHoraInicio + "\",\"" + stringDataInicio + "\")";                        
                        conn.insert(query);                        
                    } else {
                        JOptionPane.showMessageDialog(this, "Especifique a data e hora do desfile da escola com Id " + id, "Erro", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        }
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        this.setVisible(true);
    }//GEN-LAST:event_formWindowClosing

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_formWindowClosed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ConfigurarCampeonato().setVisible(true);
            }
        });
    }

    private class TableModelEscolas extends DefaultTableModel {

        public TableModelEscolas() {
            this.addColumn("ID");
            this.addColumn("Nome");
            this.addColumn("Grupo");
            this.addColumn("Data de Início");
            this.addColumn("Hora do Desfile");
        }

        public void addData(String[] data) {
            this.addRow(data);
        }
    }
    TableModelEscolas tableModel;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
